package com.example.datachange.utils;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpURLConnectionUtils {

    public static void post(String url){
        connect(url, "POST");
    }

    public static void get(String url){
        connect(url, "GET");
    }

    public static void connect(String url, String method){
        HttpURLConnection conn;
        try {
            conn = getConnection(url, method);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.connect();
            StringBuilder resp = new StringBuilder();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
                String next;
                while ((next = reader.readLine()) != null) {
                    resp.append(next);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            conn.disconnect();
            System.out.println(resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static <T> T postToEntity(String url, Map<String, Object> paramsMap, Map<String, String> headers,  Class<T> clazz) throws Exception{
        if(paramsMap!=null && !paramsMap.isEmpty()){
            StringBuilder p = new StringBuilder("?");
            Set<Map.Entry<String, Object>> entrySet = paramsMap.entrySet();
            for (Map.Entry<String, Object> entry : entrySet) {
                if(entry!=null&&entry.getKey()!=null){
                    p.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            p = new StringBuilder(p.substring(0, p.length() - 1));
            url += p;
        }
        HttpURLConnection conn = getConnection(url, "POST");
        for (String key : headers.keySet()) {
            // Set Headers
            conn.setRequestProperty(key, headers.get(key));
        }

        conn.connect();
        StringBuilder result = new StringBuilder();
        //获取响应状态
        int resultCode=conn.getResponseCode();
        if(HttpURLConnection.HTTP_OK==resultCode){
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while((line=in.readLine())!=null){
                result.append(line);
            }
            in.close();
        }
        return JSON.parseObject(result.toString(), clazz);
    }

    public static String post(String url, Map<String, Object> paramsMap, Map<String, String> headers) throws Exception{
        if(paramsMap!=null && !paramsMap.isEmpty()){
            StringBuilder p = new StringBuilder("?");
            Set<Map.Entry<String, Object>> entrySet = paramsMap.entrySet();
            for (Map.Entry<String, Object> entry : entrySet) {
                if(entry!=null&&entry.getKey()!=null){
                    p.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            p = new StringBuilder(p.substring(0, p.length() - 1));
            url += p;
        }
        HttpURLConnection conn = getConnection(url, "POST");
        for (String key : headers.keySet()) {
            // Set Headers
            conn.setRequestProperty(key, headers.get(key));
        }

        conn.connect();
        StringBuilder result = new StringBuilder();
        //获取响应状态
        int resultCode=conn.getResponseCode();
        if(HttpURLConnection.HTTP_OK==resultCode){
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while((line=in.readLine())!=null){
                result.append(line);
            }
            in.close();
        }
        return result.toString();
    }

    public static String postJson(String url, String params, Map<String, String> headers) throws Exception{
        HttpURLConnection conn = getConnection(url, "POST");
        for (String key : headers.keySet()) {
            // Set Headers
            conn.setRequestProperty(key, headers.get(key));
        }

        //放在body中的参数
        if(params!=null && !"".equals(params)){
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(params.getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        }
        conn.connect();
        StringBuilder result = new StringBuilder();
        //获取响应状态
        int resultCode=conn.getResponseCode();
        if(HttpURLConnection.HTTP_OK==resultCode){
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while((line=in.readLine())!=null){
                result.append(line);
            }
            in.close();
        }
        return result.toString();
    }

    private static HttpURLConnection getConnection(String urlString, String method) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlString);
            conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod(method);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
}
